package com.server;

import com.serializetool.Request;
import com.serializetool.Response;

import java.lang.reflect.Constructor;
import java.util.HashMap;

public class TaskHandler {
    private static HashMap<String,Class> map = new HashMap<>();
    static{
        map.put("int",int.class);
        map.put("float",float.class);
        map.put("double",double.class);
        map.put("long",long.class);
        map.put("byte",byte.class);
        map.put("string",String.class);
        map.put("boolean",boolean.class);
    }
    public Response handle(Request request){
        Response response = new Response();
        try{
            String className = request.getClassName();
            String methodName = request.getMethodName();
            String[] parameterTypes = request.getParameterTypes();
            Object[] parameterValues = request.getParameters();
            Class classType = Class.forName(className);
            Constructor constructor = classType.getConstructor();
            int len = parameterTypes.length;;
            Class[] parameterClasses = new Class[len];
            for(int i=0;i<len;i++){
                parameterClasses[i] = map.get(parameterTypes[i]);
            }
            Object result = classType.getMethod(methodName, parameterClasses).invoke(constructor.newInstance(),parameterValues);
            response.setResult(result);
            System.out.println("调用成功");
        }
        catch (Exception e){
            System.out.println("调用失败:");
            e.printStackTrace();
            response.setErrorMsg(e);
        }finally {
            response.setTaskId(request.gettaskId());
            return response;
        }
    }
}
